/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.hs.srm.admin.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.hs.srm.admin.common.config.KaptchaConfig;
import com.hs.srm.admin.modules.sys.shiro.MyUsernamePasswordToken;
import com.hs.srm.base.modules.sys.entity.SysMenuEntity;
import com.hs.srm.base.modules.sys.form.LoginForm;
import com.hs.srm.base.modules.sys.service.SysMenuService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.base.modules.sys.shiro.ShiroUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.common.validator.ValidatorUtils;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
public class SysLoginController extends AbstractController {
	@Autowired
	private Producer producer;
	@Autowired
	private KaptchaConfig kaptchaConfig;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("/getCaptcha")
	public void captcha(HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字验证码
		String text = this.producer.createText();
		// 生成图片验证码
		BufferedImage image = this.producer.createImage(text);
		// 保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.close();
	}

	@RequestMapping("/sys/index")
	public String index(Model model) {
		// 获取菜单列表
		List<SysMenuEntity> menuList = this.sysMenuService.getUserMenuList(this.getUserId());
		model.addAttribute("currUser", this.getUser());
		model.addAttribute("avatar", this.sysUserService.selectById(this.getUserId()).getAvatar());
		model.addAttribute("menuList", menuList);
		return "index";
	}

	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(LoginForm loginForm) {
		// 校验类型
		ValidatorUtils.validateEntity(loginForm);
        //判断是否需要验证吗
		if(Boolean.parseBoolean(this.kaptchaConfig.getHasCaptcha())) {
			String captcha = loginForm.getCaptcha();
			String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
			if(!captcha.equalsIgnoreCase(kaptcha)) {
				return R.error("验证码不正确");
			}
		}

		try {
			Subject subject = ShiroUtils.getSubject();
			MyUsernamePasswordToken token = new MyUsernamePasswordToken(loginForm.getUsername(),
					loginForm.getPassword());
			token.setRememberMe(loginForm.isRemember());
			subject.login(token);
		} catch(UnknownAccountException e) {
			return R.error(e.getMessage());
		} catch(IncorrectCredentialsException e) {
			return R.error("账号或密码不正确");
		} catch(LockedAccountException e) {
			return R.error("账号已被锁定,请联系管理员");
		} catch(AuthenticationException e) {
			return R.error("账户验证失败");
		}

		return R.ok();
	}

	/**
	 * 跳转到登录页面
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		model.addAttribute("hasCaptcha", this.kaptchaConfig.getHasCaptcha());
		return "login";
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login";
	}

}
